#include "systimer.h"

struct System_Timer systemTimer;

static void systick_init(void)
{
	if (SysTick_Config(SystemCoreClock / 1000U))
	{
		while (1)
		{
					
		}
	}	
	NVIC_SetPriority(SysTick_IRQn, 0x00U);
}

static void system_timer_func(void)
{
	systemTimer.systemCnt++;
	
	if(systemTimer.systemCnt > 0xFEFFFFFF)
	{
		systemTimer.systemCnt = 0;
	}
	
	if((systemTimer.systemCnt % 5) == 0)
	{
		systemTimer.flag5ms = 1;
	}
	if((systemTimer.systemCnt % 10) == 0)
	{
		systemTimer.flag10ms = 1;
	}
	if((systemTimer.systemCnt % 20) == 0)
	{
		systemTimer.flag20ms = 1;
	}
	if((systemTimer.systemCnt % 50) == 0)
	{
		systemTimer.flag50ms = 1;
	}
	if((systemTimer.systemCnt % 100) == 0)
	{
		systemTimer.flag100ms = 1;
	}
	if((systemTimer.systemCnt % 200) == 0)
	{
		systemTimer.flag200ms = 1;
	}
	if((systemTimer.systemCnt % 500) == 0)
	{
		systemTimer.flag500ms = 1;
	}
	if((systemTimer.systemCnt % 1000) == 0)
	{
		systemTimer.flag1000ms = 1;
	}
}

void delay_us(uint32_t us)
{
    uint64_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;

    ticks = us * (reload / (1000000 / 1000));
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
}

void delay_ms(uint32_t ms)
{
	while(ms--)
	{
		delay_us(1000);
	}
}

void systimer_init(void)
{
	systick_init();
}

/*!
    \brief      this function handles SysTick exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SysTick_Handler(void)
{
	system_timer_func();
}
